package com.leonardo.beanme.metadatahandlers;

import java.util.Enumeration;
import java.util.Hashtable;

import com.leonardo.beanme.exceptions.TypeInstantiationException;
import com.leonardo.beanme.fields.InputField;
import com.leonardo.beanme.metadatahandlers.tags.FieldTagHandler;
import com.leonardo.beanme.metadatahandlers.tags.FieldTypeTagHandler;
import com.leonardo.beanme.metadatahandlers.tags.GetterTagHandler;
import com.leonardo.beanme.metadatahandlers.tags.SetterTagHandler;
import com.leonardo.beanme.model.BeanForm;

public class FieldMetadataContainer {
	
	private Hashtable handlers = new Hashtable();
	
	public void addItselfIn(BeanForm form) throws TypeInstantiationException, ClassNotFoundException {
		try {
			InputField inputField = (InputField)(this.getFieldType().newInstance());
			Enumeration it = handlers.elements(); 
			while(it.hasMoreElements()) {
				TagHandler handler = (TagHandler) it.nextElement();
				handler.handle(inputField, form);
			}
			form.putField(this, inputField);
			form.append(inputField.getField());
		} catch (InstantiationException ex) {
			throw new TypeInstantiationException(this.getFieldType());
		} catch (IllegalAccessException ex) {
			throw new TypeInstantiationException(this.getFieldType());
		} 
	}
	
	public void addHandler(TagHandler handler) {
		handlers.put(handler.getClass(), handler);
	}
	
	/*Mandatory Fields*/
	public String getGetter() {
		return ((GetterTagHandler) handlers.get(GetterTagHandler.class)).getInnerText();
	}
	
	public String getSetter() {
		return ((SetterTagHandler) handlers.get(SetterTagHandler.class)).getInnerText();
	}
	
	public Class getFieldType() throws ClassNotFoundException {
		String className = ((FieldTypeTagHandler) handlers.get(FieldTypeTagHandler.class)).getInnerText();
		return Class.forName(className);
	}
	
	public String getName() {
		return ((FieldTagHandler) handlers.get(FieldTagHandler.class)).getName();
	}
	
	/*End of mandatory fields*/
	
	public Enumeration getHandlers() {
		return handlers.elements();
	}
	
	public boolean constains(Class key) {
		return handlers.containsKey(key);
	}
	
	public TagHandler get(Class key) {
		return (TagHandler) handlers.get(key);
	}
	
}
